<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CouponShop extends Model
{
    protected $dateFormat = 'U';
    //
    protected $table = "lexiang_coupon_shop";

    /**
     * 注册商户
     */
    public function register($data)
    {
    	$this->shop_name = $data['shop_name'];
    	// $this->tel = $data['tel'] ?? '';
        $this->avatar = $data['avatar'];
    	$this->openid = $data['openid'];
    	if($this->save()){
    		return ['success'=>true,'code'=>'000','message'=>'认证成功！','data'=>[
                'id'=>$this->id,
                'shop_name'=>$this->shop_name,
                'avatar'=>$this->avatar,
                'openid'=>$this->openid,
                'tel'=>$this->tel,
                'amount'=>$this->amount,
                'position'=>$this->position,
                'clerk_shop_id'=>$this->clerk_shop_id ?? 0,
                'parent_shopname'=>'未授权',
            ]];
    	}else{
    		return ['success'=>false,'code'=>'006','message'=>'保存出错，请稍后再试'];
    	}
    }

    /**
     * 授权记录商户
     */
    public function auth($data,$openid=false)
    {
        $selfInfo = $this->where('openid',$openid)->first();
    	if(!$selfInfo){
    		return $this->register($data);
    	}
    	foreach ($data as $key => $value) {
           if($key=='shop_name'){
              continue;
           }
    		$selfInfo->$key = $value;
    	}

    	if($selfInfo->save()){
            if($selfInfo->position==2){
                $shopname = $this->where('id',$selfInfo->clerk_shop_id)->value('shop_name');
            }else{
                $shopname = '未授权';
            }
    		return ['success'=>true,'code'=>'000','message'=>'授权成功！','data'=>[
                'id'=>$selfInfo->id,
                'shop_name'=>$selfInfo->shop_name,
                'avatar'=>$selfInfo->avatar,
                'openid'=>$selfInfo->openid,
                'tel'=>$selfInfo->tel,
                'amount'=>$selfInfo->amount ?? 0,
                'position'=>$selfInfo->position,
                'clerk_shop_id'=>$selfInfo->clerk_shop_id,
                'parent_shopname'=>$shopname,
            ]];
    	}else{
    		return ['success'=>false,'code'=>'006','message'=>'授权出错，请稍后再试'];
    	}
    }

    public function getAddressAttribute($v)
    {
        return CouponItem::where('shop_id',$this->id)->value('address')??'未填写';
    }

}
